<script setup lang="ts">
import type { MachineGroup } from '@/apis/model/group.ts'
import type { FormInstance } from '@arco-design/web-vue'
import {
  addComputeMachineGroupApi,
  getComputeMachineGroupDetailApi,
  updateComputeMachineGroupApi,
} from '@/apis/modules/group.ts'
import {
  getBaremetalNodeListApi,
  getManageHypervisorsListApi,
} from '@/apis/modules/node'
import { buildColumns } from '@/utils/table.ts'
import { Message } from '@arco-design/web-vue'

interface IEmit {
  (e: 'success'): void
}

interface IProps {
  record?: MachineGroup
  type: 1 | 2
}

const props = defineProps<IProps>()
const emit = defineEmits<IEmit>()
const visible = defineModel<boolean>({ required: true })

const { allRegionOptions } = useRegions()

const formRef = ref<FormInstance>()
const formRules = {
  name: [{ required: true, message: '请输入分组名称' }],
  region_id: [{ required: true, message: '请选择区域' }],
}
const formData = ref({
  id: '',
  name: '',
  region_id: '',
  status: 1,
})

const selectedKeys = ref<string[]>([])
// const nodesErrorMsg = ref('')
const nodes = ref<{ id: string, ip: string, tag: string }[]>([])
const searchTag = ref('')

/**
 * 根据type类型获取节点列表
 */
async function getNodes() {
  if (!formData.value.region_id) {
    return
  }
  if (props.type === 1) {
    // 获取云服务器节点列表
    const res = await getManageHypervisorsListApi({
      tag: searchTag.value,
      region_id: formData.value.region_id,
    })
    nodes.value = (res.list || [])
      .filter(
        item =>
          item.machine_group_id === '0'
          || item.machine_group_id === formData.value.id,
      )
      .map((item) => {
        return { id: item.id!, ip: item.host_ip!, tag: item.tag! }
      })
    return
  }
  // 获取裸金属节点列表
  const res = await getBaremetalNodeListApi({
    tag: searchTag.value,
    region_id: formData.value.region_id,
  })
  nodes.value = (res.list || [])
    .filter(
      item =>
        (item.machine_group_id === '0' && item.status === 1)
        || item.machine_group_id === formData.value.id,
    )
    .map((item) => {
      return { id: item.id!.toString(), ip: item.ipmi!, tag: item.tag! }
    })
}

function handleRegionChange() {
  nodes.value = []
}

watch(
  () => formData.value.region_id,
  () => getNodes(),
)

// watch(selectedKeys, () => {
//   if (selectedKeys.value.length) {
//     nodesErrorMsg.value = ''
//   }
// })

/**
 * 提交保存
 */
async function handleSubmit() {
  const err = await formRef.value!.validate()
  if (err) {
    return false
  }
  // if (!selectedKeys.value.length) {
  //   nodesErrorMsg.value = '请添关联节点'
  //   return false
  // }
  const data = {
    ...formData.value,
    type: props.type,
    host_uuid: [] as string[],
    host_id: [] as string[],
  }
  if (props.type === 1) {
    data.host_uuid = selectedKeys.value
  } else {
    data.host_id = selectedKeys.value
  }
  const fn = props.record
    ? updateComputeMachineGroupApi
    : addComputeMachineGroupApi
  await fn(data)
  emit('success')
  Message.success(props.record ? '编辑成功' : '新建成功')
  return true
}

async function handleOpen() {
  if (!props.record) {
    return
  }
  await getNodes()
  const res = await getComputeMachineGroupDetailApi({ id: props.record.id })
  formData.value = {
    id: props.record.id! as string,
    name: res.info!.name!,
    region_id: res.info!.region_id! as any,
    status: res.info!.status!,
  }
  selectedKeys.value
    = props.type === 1
      ? res.info!.host_uuid || []
      : ((res.info!.host_id || []) as string[])
}

function handleClose() {
  formRef.value!.resetFields()
  formData.value.id = ''
  nodes.value = []
  // nodesErrorMsg.value = ''
  selectedKeys.value = []
  searchTag.value = ''
}
</script>

<template>
  <a-drawer
    v-model:visible="visible"
    width="480px"
    :title="record ? '编辑分组' : '新建分组'"
    :mask-closable="false"
    :on-before-ok="handleSubmit"
    @close="handleClose"
    @open="handleOpen"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item
        label="分组名称"
        field="name"
        required
        hide-asterisk
      >
        <a-input
          v-model.trim="formData.name"
          placeholder="请输入分组名称"
          show-word-limit
          :max-length="40"
        />
      </a-form-item>
      <a-form-item
        label="所属区域"
        field="region_id"
        required
        hide-asterisk
      >
        <a-select
          v-model.trim="formData.region_id"
          placeholder="请选择区域"
          :options="allRegionOptions"
          :disabled="!!record"
          @change="handleRegionChange"
        />
      </a-form-item>
      <a-form-item
        label="关联节点"
        required
        hide-asterisk
      >
        <!-- <template #extra>
          <span class="text-color-danger">{{ nodesErrorMsg }}</span>
        </template> -->
        <div class="flex flex-col space-y-2">
          <a-input
            v-model="searchTag"
            placeholder="请输入标签搜索"
            @change="getNodes"
          />
          <a-table
            v-model:selected-keys="selectedKeys"
            row-key="id"
            :scroll="{ y: 350 }"
            :pagination="false"
            :row-selection="{ type: 'checkbox', showCheckedAll: true }"
            :columns="
              buildColumns([
                { title: 'IP地址', dataIndex: 'ip' },
                { title: '标签', dataIndex: 'tag' },
              ])
            "
            :data="nodes"
          />
        </div>
      </a-form-item>
      <a-form-item
        label="状态"
        field="status"
        required
        hide-asterisk
      >
        <a-radio-group
          v-model="formData.status"
          :options="[
            { label: '启用', value: 1 },
            { label: '禁用', value: 2 },
          ]"
        />
      </a-form-item>
    </a-form>
  </a-drawer>
</template>
